#include <gtest/gtest.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
#include <chrono>
#include <thread>
#include <filesystem>

// 包含回测引擎的头文件
#include "backtest/backtest_engine.h"
#include "backtest/data_loader.h"
#include "market_data/market_data.h"
#include "strategy/strategy_base.h"
#include "utils/json_utils.h"

namespace fs = std::filesystem;

// 创建一个简单的测试策略类
class TestStrategy : public StrategyBase {
public:
    TestStrategy(const std::string& name, const json& params)
        : StrategyBase(name), window_size_(params.value("window_size", 5)), threshold_(params.value("threshold", 0.01)) {}

    void on_market_data(const MarketData& data) override {
        // 简单的策略逻辑：如果价格上涨超过阈值，买入；如果价格下跌超过阈值，卖出
        if (price_history_.size() >= window_size_) {
            double avg_price = 0.0;
            for (size_t i = 0; i < window_size_; ++i) {
                avg_price += price_history_[price_history_.size() - 1 - i];
            }
            avg_price /= window_size_;

            double current_price = data.price;
            double price_change = (current_price - avg_price) / avg_price;

            if (price_change > threshold_) {
                // 价格上涨超过阈值，发出买入信号
                Order buy_order;
                buy_order.symbol = data.symbol;
                buy_order.price = current_price;
                buy_order.quantity = 100;
                buy_order.side = OrderSide::BUY;
                buy_order.type = OrderType::LIMIT;
                buy_order.timestamp = data.timestamp;
                
                emit_signal(Signal{SignalType::BUY, data.symbol, current_price, 100, data.timestamp});
            } else if (price_change < -threshold_) {
                // 价格下跌超过阈值，发出卖出信号
                Order sell_order;
                sell_order.symbol = data.symbol;
                sell_order.price = current_price;
                sell_order.quantity = 100;
                sell_order.side = OrderSide::SELL;
                sell_order.type = OrderType::LIMIT;
                sell_order.timestamp = data.timestamp;
                
                emit_signal(Signal{SignalType::SELL, data.symbol, current_price, 100, data.timestamp});
            }
        }

        // 更新价格历史
        price_history_.push_back(data.price);
        if (price_history_.size() > window_size_ * 2) {
            price_history_.erase(price_history_.begin());
        }
    }

private:
    int window_size_;
    double threshold_;
    std::vector<double> price_history_;
};

// 测试回测引擎的基本功能
TEST(BacktestTest, BasicFunctionality) {
    // 读取配置文件
    std::string config_path = "tests/test_data/backtest_config.json";
    std::ifstream config_file(config_path);
    ASSERT_TRUE(config_file.is_open()) << "Failed to open config file: " << config_path;
    
    json config;
    config_file >> config;
    config_file.close();

    // 创建数据加载器
    std::string data_path = "tests/" + config["market_data"]["file_path"].get<std::string>();
    auto data_loader = std::make_shared<CSVDataLoader>(data_path);
    ASSERT_TRUE(fs::exists(data_path)) << "Market data file does not exist: " << data_path;

    // 创建策略
    auto strategy_params = config["strategy"]["parameters"];
    auto strategy = std::make_shared<TestStrategy>(config["strategy"]["name"], strategy_params);

    // 创建回测引擎
    BacktestEngine engine;
    engine.set_data_loader(data_loader);
    engine.add_strategy(strategy);
    
    // 设置回测参数
    engine.set_initial_balance(config["trading"]["initial_balance"].get<double>());
    engine.set_commission_rate(config["trading"]["commission_rate"].get<double>());
    
    // 运行回测
    std::string start_time = config["market_data"]["start_time"];
    std::string end_time = config["market_data"]["end_time"];
    std::string symbol = config["market_data"]["symbol"];
    
    BacktestResult result = engine.run(symbol, start_time, end_time);
    
    // 验证回测结果
    EXPECT_GT(result.end_balance, 0.0) << "End balance should be greater than zero";
    EXPECT_GE(result.trades.size(), 0) << "There should be at least some trades";
    
    // 输出回测结果
    std::cout << "Backtest Results:" << std::endl;
    std::cout << "  Start Balance: " << result.start_balance << std::endl;
    std::cout << "  End Balance: " << result.end_balance << std::endl;
    std::cout << "  Profit/Loss: " << result.end_balance - result.start_balance << std::endl;
    std::cout << "  Return: " << (result.end_balance / result.start_balance - 1.0) * 100.0 << "%" << std::endl;
    std::cout << "  Number of Trades: " << result.trades.size() << std::endl;
}

// 测试回测引擎的性能
TEST(BacktestTest, Performance) {
    // 读取配置文件
    std::string config_path = "tests/test_data/backtest_config.json";
    std::ifstream config_file(config_path);
    ASSERT_TRUE(config_file.is_open()) << "Failed to open config file: " << config_path;
    
    json config;
    config_file >> config;
    config_file.close();

    // 创建数据加载器
    std::string data_path = "tests/" + config["market_data"]["file_path"].get<std::string>();
    auto data_loader = std::make_shared<CSVDataLoader>(data_path);
    
    // 创建策略
    auto strategy_params = config["strategy"]["parameters"];
    auto strategy = std::make_shared<TestStrategy>(config["strategy"]["name"], strategy_params);

    // 创建回测引擎
    BacktestEngine engine;
    engine.set_data_loader(data_loader);
    engine.add_strategy(strategy);
    
    // 设置回测参数
    engine.set_initial_balance(config["trading"]["initial_balance"].get<double>());
    engine.set_commission_rate(config["trading"]["commission_rate"].get<double>());
    
    // 运行回测并测量性能
    std::string start_time = config["market_data"]["start_time"];
    std::string end_time = config["market_data"]["end_time"];
    std::string symbol = config["market_data"]["symbol"];
    
    auto start = std::chrono::high_resolution_clock::now();
    BacktestResult result = engine.run(symbol, start_time, end_time);
    auto end = std::chrono::high_resolution_clock::now();
    
    std::chrono::duration<double> elapsed = end - start;
    std::cout << "Backtest execution time: " << elapsed.count() << " seconds" << std::endl;
    
    // 验证性能
    EXPECT_LT(elapsed.count(), 1.0) << "Backtest should complete in less than 1 second";
}

// 主函数
int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}